/**
 * 游戏主界面activity
 */
package com.key;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.key.util.GameParams;
import com.key.util.UserSystemData;

public class KeyChineseChessMainMenuActivity extends Activity implements
		OnClickListener {

	//开始游戏、设置、帮助、退出按钮
	private ImageButton startGameButton, settingButton, helpButton, exitButton;

	//游戏设置popwindow
	private PopupWindow popupWindow = null;

	/**
	 * 取得音乐大小
	 * @return
	 */
	public int getMusicDegree() {
		if (UserSystemData.keyMusic.getMusicChecked() == true) {
			return UserSystemData.keyMusic.getMusicDegree();
		}
		return -1;
	}

	/**
	 * 取得音效大小
	 * @return
	 */
	public int getSingleDegree() {
		if (UserSystemData.keyMusic.getSingleChecked() == true) {
			return UserSystemData.keyMusic.getSingleDegree();
		}
		return -1;
	}

	/**
	 * 初始化用户信息
	 */
	private void initUserInfo() {
		UserSystemData.UserInfo.init();
		UserSystemData.UserInfo.read(UserSystemData.strResultPath);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.key_main_menu);

		initView();//初始化界面
		initUserInfo();//初始化用户信息
		initMusic();//初始化音乐
		initSoundPool();//初始化音效池
	}
	
	/**
	 * 初始化音效控制类，播放音乐
	 */
	public void initMusic() {
		GameParams.chessAudio = new KeyChineseChessAudio();
		GameParams.chessAudio.init(this, 7);
		GameParams.chessAudio.initMedia(this, R.raw.agreatgiantplay);
		GameParams.chessAudio.setMediaLoop();
		GameParams.chessAudio.playMedia();
		GameParams.chessAudio.adjustVolume();
		GameParams.chessAudio.setMusicMute(false);
	}
	
	/**
	 * 初始化音效类
	 */
	public void initSoundPool() {
		GameParams.soundCapture = GameParams.chessAudio.loadRaw(this, R.raw.capture);
		GameParams.soundLoss = GameParams.chessAudio.loadRaw(this, R.raw.loss);
		GameParams.soundMove = GameParams.chessAudio.loadRaw(this, R.raw.move);
		GameParams.soundNewGame = GameParams.chessAudio.loadRaw(this, R.raw.newgame);
		GameParams.soundPromote = GameParams.chessAudio.loadRaw(this, R.raw.promote);
		GameParams.soundWin = GameParams.chessAudio.loadRaw(this, R.raw.win);
		GameParams.soundEat = GameParams.chessAudio.loadRaw(this, R.raw.eat);
	}

	/**
	 * 初始化界面
	 */
	private void initView() {

		startInitView();//开始按钮初始化
		setInitView();//设置按钮初始化
		aboutInitView();//帮助按钮初始化
		exitInitView();//退出按钮初始化
		GameParams.mainActivity = this;//加入游戏参数
	}

	/**
	 * 开始按钮初始化
	 */
	private void startInitView() {

		startGameButton = (ImageButton) findViewById(R.id.gameStartButton);
		startGameButton.setOnClickListener(this);
		startGameButton.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.consolegame_down_btn));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.consolegame_up_btn));
				}
				return false;
			}
		});
	}

	/**
	 * 设置按钮初始化
	 */
	private void setInitView() {

		settingButton = (ImageButton) findViewById(R.id.gameSetButton);
		settingButton.setOnClickListener(this);
		settingButton.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.setgame_down_btn));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.setgame_up_btn));
				}
				return false;
			}
		});
	}

	/**
	 * 游戏说明初始化
	 */
	private void aboutInitView() {

		helpButton = (ImageButton) findViewById(R.id.gameAboutButton);
		helpButton.setOnClickListener(this);
		helpButton.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.aboutgame_down_btn));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.aboutgame_up_btn));
				}
				return false;
			}
		});
	}

	/**
	 * 退出按钮初始化
	 */
	private void exitInitView() {

		exitButton = (ImageButton) findViewById(R.id.gameExitButton);
		exitButton.setOnClickListener(this);
		exitButton.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.exitgame_down_btn));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.exitgame_up_btn));
				}
				return false;
			}
		});
	}

	public void onClick(View v) {

		Intent gameIntent = null;
		switch (v.getId()) {
		case R.id.gameStartButton://单机游戏
			gameIntent = new Intent(this,
					KeyChineseChessSingleGameActivity.class);
			this.startActivity(gameIntent);
			break;
		case R.id.gameSetButton://游戏设置
			createSettingDialog(UserSystemData.DEGREE_DIALOG, v);
			break;
		case R.id.gameAboutButton://游戏说明
			gameIntent = new Intent(this,
					KeyChineseChessAboutMenuActivity.class);
			this.startActivity(gameIntent);
			break;
		case R.id.gameExitButton://移除游戏
			UserSystemData.UserInfo.write();
			this.finish();
			android.os.Process.killProcess(android.os.Process.myPid());
			break;
		default:
			break;
		}
	}

	/**
	 * 创建游戏设置popwindow
	 * @param id
	 * @param v
	 */
	private void createSettingDialog(int id, View v) {

		switch (id) {
		case UserSystemData.DEGREE_DIALOG:
			initDialog();
			createDialog(v);
			break;
		default:
			break;
		}
	}

	/**
	 * 初始化游戏设置对话框
	 */
	private void initDialog() {

		ViewGroup vg = (ViewGroup) getLayoutInflater().inflate(
				R.layout.key_popwindow_menu, null);
		if (popupWindow == null) {
			popupWindow = new PopupWindow(vg, LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
		}
		if (popupWindow.isShowing()) {
			popupWindow.dismiss();
		}

		CheckBox music = (CheckBox) vg.findViewById(R.id.checkbox_music_degree);
		CheckBox single = (CheckBox) vg
				.findViewById(R.id.checkbox_single_degree);

		SeekBar musicBar = (SeekBar) vg.findViewById(R.id.seekbar_Music);
		SeekBar singleBar = (SeekBar) vg.findViewById(R.id.seekbar_Single);

		//初始化信息
		musicBar.setProgress(UserSystemData.keyMusic.getMusicDegree());
		singleBar.setProgress(UserSystemData.keyMusic.getSingleDegree());
		if (UserSystemData.keyMusic.getMusicChecked() == true) {
			music.setChecked(true);
		} else {
			music.setChecked(false);
		}
		if (UserSystemData.keyMusic.getSingleChecked() == true) {
			single.setChecked(true);
		} else {
			single.setChecked(false);
		}

		//设置控制
		music.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (isChecked) {
					UserSystemData.keyMusic.setMusicChecked(true);
					GameParams.chessAudio.adjustVolume();
					GameParams.chessAudio.setMusicMute(true);
				} else {
					UserSystemData.keyMusic.setMusicChecked(false);
					GameParams.chessAudio.setMusicMute(false);
				}
			}
		});
		single.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (isChecked) {
					UserSystemData.keyMusic.setSingleChecked(true);
				} else {
					UserSystemData.keyMusic.setSingleChecked(false);
				}
			}
		});

		musicBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			public void onStartTrackingTouch(SeekBar musicBar) {
				// TODO Auto-generated method stub
			}

			public void onProgressChanged(SeekBar musicBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				int i = musicBar.getProgress();
				if (i >= 0) {
					UserSystemData.keyMusic.setMusicDegree(i);
					GameParams.chessAudio.adjustVolume();
				}
				if (i > 9) {
					musicBar.setProgress(9);
				} else if (i < 1) {
					musicBar.setProgress(1);
				}
			}

			public void onStopTrackingTouch(SeekBar musicBar) {
				// TODO Auto-generated method stub
				int i = musicBar.getProgress();
				if (i >= 0) {
					UserSystemData.keyMusic.setMusicDegree(i);
					GameParams.chessAudio.adjustVolume();
				}
			}
		});
		singleBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			public void onStartTrackingTouch(SeekBar singleBar) {
				// TODO Auto-generated method stub
			}

			public void onProgressChanged(SeekBar singleBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				int i = singleBar.getProgress();
				if (i >= 0) {
					UserSystemData.keyMusic.setSingleDegree(i);
				}
				if (i > 9) {
					singleBar.setProgress(9);
				} else if (i < 1) {
					singleBar.setProgress(1);
				}
			}

			public void onStopTrackingTouch(SeekBar singleBar) {
				// TODO Auto-generated method stub
				int i = singleBar.getProgress();
				if (i >= 0) {
					UserSystemData.keyMusic.setSingleDegree(i);
				}
			}
		});

	}

	/**
	 * 显示游戏设置对话框
	 * @param v
	 */
	private void createDialog(View v) {

		popupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
	}

	/**
	 * 屏蔽返回键
	 */
	@Override
	public boolean onKeyDown(int kCode, KeyEvent kEvent) {

		if (kCode == KeyEvent.KEYCODE_BACK) {
			if (popupWindow != null) {
				if (popupWindow.isShowing()) {
					popupWindow.dismiss();
					return false;
				}
			}
			return true;
		}
		return super.onKeyDown(kCode, kEvent);
	}

	/**
	 * 写用户信息到游戏data目录
	 * @param listResult
	 * @return
	 */
	public boolean writeUserInfoResultPath(List<String> listResult) {

		try {
			String content = "";
			for (int i = 0; i < listResult.size(); i++) {
				content = content + listResult.get(i) + "\n";
			}

			FileOutputStream fout = openFileOutput(
					UserSystemData.strResultPath, MODE_PRIVATE);
			fout.write(content.getBytes());
			fout.close();

			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 从用户读用户信息到游戏
	 * @param listResult 
	 */
	public void readUserInfoResultPath(List<String> listResult) {
		try {
			BufferedReader reader = null;
			try {
				FileInputStream fis = openFileInput(UserSystemData.strResultPath);
				BufferedInputStream in = new BufferedInputStream(fis);
				in.mark(4);
				byte[] first3bytes = new byte[3];
				in.read(first3bytes);
				in.reset();
				if (first3bytes[0] == (byte) 0xEF
						&& first3bytes[1] == (byte) 0xBB
						&& first3bytes[2] == (byte) 0xBF) {// utf-8
					reader = new BufferedReader(new InputStreamReader(in,
							"utf-8"));
				} else if (first3bytes[0] == (byte) 0xFF
						&& first3bytes[1] == (byte) 0xFE) {
					reader = new BufferedReader(new InputStreamReader(in,
							"unicode"));
				} else if (first3bytes[0] == (byte) 0xFE
						&& first3bytes[1] == (byte) 0xFF) {
					reader = new BufferedReader(new InputStreamReader(in,
							"utf-16be"));
				} else if (first3bytes[0] == (byte) 0xFF
						&& first3bytes[1] == (byte) 0xFF) {
					reader = new BufferedReader(new InputStreamReader(in,
							"utf-16le"));
				} else {
					reader = new BufferedReader(
							new InputStreamReader(in, "GBK"));
				}

				String str = reader.readLine();
				while (str != null) {
					listResult.add(str);
					str = reader.readLine();
				}
				listResult.add(str);
				reader.close();

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				return;
			} catch (IOException e) {
				return;
			}

			// inputStream.close();
		} catch (Exception e) {
			return;
		}
	}
}
